const _ = require('lodash')
const path = require('path')
const Dao = require(path.join(process.cwd(), 'dao/Dao'))
const PermissionAPIDao  = require(path.join(process.cwd(), 'dao/PermissionAPIDao'))

// 权限验证函数
module.exports.authRight = function(rid, serviceName, actionName, cb) {
    PermissionAPIDao.authRight(rid, serviceName, actionName, function(err, pass) {
        cb(err, pass)
    })
}

// 获取所有用户的角色 & 权限
module.exports.getAllRoles = function (cb) {
    Dao.list('RoleModel', null, (err, roles) => {
        if (err) cb('获取角色数据失败')
        PermissionAPIDao.list( (err, permissions) => {
            if (err) return cb('获取权限数据失败')
			let permissionKeys = _.keyBy(permissions,'ps_id')
            let rolesResult = []
            for (idx in roles) {
                role = roles[idx]
                permissionIds = role.ps_ids.split(',')
                roleResult = {
                    id: role.role_id,
                    roleName: role.role_name,
                    roleDesc: role.role_desc,
                    children: []
                }
                roleResult.children = _.values(getPermissionsResult(permissionKeys,permissionIds));
				rolesResult.push(roleResult);
            }
            cb(null, rolesResult)
        })
    })
}

function getPermissionsResult(permissionKeys,permissionIds) {
	var permissionsResult = {};

	// 处理一级菜单
	for(idx in permissionIds) {
		if(!permissionIds[idx] || permissionIds[idx] == "") continue;
		permissionId = parseInt(permissionIds[idx]);
		permission = permissionKeys[permissionId];
		if(permission && permission.ps_level == 0) {
			permissionsResult[permission.ps_id] = {
				"id":permission.ps_id,
				"authName":permission.ps_name,
				"path":permission.ps_api_path,
				"children":[]
			};
		}
	}

	// 临时存储二级返回结果
	tmpResult = {};
	// 处理二级菜单
	for(idx in permissionIds) {
		if(!permissionIds[idx] || permissionIds[idx] == "") continue;
		permissionId = parseInt(permissionIds[idx]);
		permission = permissionKeys[permissionId];
		if(permission && permission.ps_level == 1) {
			parentPermissionResult = permissionsResult[permission.ps_pid];
			if(parentPermissionResult) {
				tmpResult[permission.ps_id] = {
					"id":permission.ps_id,
					"authName":permission.ps_name,
					"path":permission.ps_api_path,
					"children":[]
				}
				parentPermissionResult.children.push(tmpResult[permission.ps_id]);
			}
		}
	}

	// 处理三级菜单
	for(idx in permissionIds) {
		if(!permissionIds[idx] || permissionIds[idx] == "") continue;
		permissionId = parseInt(permissionIds[idx]);
		permission = permissionKeys[permissionId];
		if(permission && permission.ps_level == 2) {

			parentPermissionResult = tmpResult[permission.ps_pid];

			if(parentPermissionResult) {
				
				parentPermissionResult.children.push({
					"id":permission.ps_id,
					"authName":permission.ps_name,
					"path":permission.ps_api_path
				});
			}
		}
	}
	return permissionsResult;
}

// 创建角色
module.exports.createRole = function (params, cb) {
	if (!params.roleName) return cb('角色名称不能为空')
	if (!params.roleDesc) params.roleDesc = ""

	Dao.create('RoleModel', {
		role_name: params.roleName,
		role_desc: params.roleDesc,
		ps_ids: ""
	}, (err, role) => {
		if (err) return cb('创建角色失败')
		cb(null, {
			roleId: role.role_id,
			roleName: role.role_name,
			roleDesc: role.role_desc
		})
	})
}

// 通过角色ID获取角色详情
module.exports.getRoleById = function (id, cb) {
	if (!id) return cb('角色ID不能为空')
	if (isNaN(parseInt(id))) return cb('角色ID必须为数字')

	Dao.show("RoleModel", id, (err, role) => {
		if (err) return cb('获取角色详情失败')
		cb(null, {
			roleId: role.role_id,
			roleName: role.role_name,
			roleDesc: role.role_desc,
			rolePermissionDesc: role.ps_ca
		})
	})
}

// 更新角色信息
module.exports.updateRole = function (params, cb) {
	if (!params) return cb(null, 400, '参数不能为空')
	if (!params.id) return cb(null, 400, '角色ID不能为空')
    if (isNaN(parseInt(params.id))) return cb(null, 400, '角色ID必须为数字')
    if (!params.roleName) return cb(null, 400, '角色名称不能为空')

	let updateInfo = {}
	if (params.roleName) {
		updateInfo['role_name'] = params.roleName
	}
	if (params.roleDesc) {
		updateInfo['role_desc'] = params.roleDesc
	}

	Dao.update('RoleModel', params.id, updateInfo, (err, newRole) => {
		if (err) return cb('更新角色信息失败')
		cb(null, {
			roleId: newRole.role_id,
			roleName: newRole.role_name,
			roleDesc: newRole.role_desc,
			rolePermissionDesc: newRole.ps_ca
		})
	})
}

// 删除角色
module.exports.deleteRole = function (id, cb) {
	if (!id) return cb('角色ID不能为空')
	if (isNaN(parseInt(id))) return cb(null, 400, '角色ID必须为数字')

	Dao.destroy('RoleModel', id, (err) => {
		if (err) return cb('删除角色失败')
		cb(null, true)
	})

}

// 为角色授权
module.exports.updateRoleRight = function (rid, rights, cb) {
	if(!rid) return cb("角色ID不能为空");
	if(isNaN(parseInt(rid))) return cb("角色ID必须为数字");

	Dao.update('RoleModel', rid, {
		ps_ids: rights
	}, (err, newRole) => {
		if(err) return cb("更新权限失败")
		cb(null, {
			roleId: newRole.role_id,
			roleName: newRole.role_name
		})
	})
}

// 删除权限
module.exports.deleteRoleRight = function (id, deleteRightId, cb) {
	Dao.findOne('RoleModel', {
		role_id: id
	}, (err, role) => {
		if (err || !role) return cb('获取角色信息失败', false)
		let ps_ids = role.ps_ids.split(',')
		let new__ps_ids = []
		for (idx in ps_ids) {
			ps_id = ps_ids[idx]
			if (parseInt(deleteRightId) == parseInt(ps_id)) {
				continue
			}
			new__ps_ids.push(ps_id)
		}
		let new_ps_ids_string = new__ps_ids.join(',')
		role.ps_ids = new_ps_ids_string
		role.save( function (err, newRole) {
			if(err) return cb("删除权限失败");
			PermissionAPIDao.list(function(err,permissions){
				if(err) return cb("获取权限数据失败")
				permissionIds = newRole.ps_ids.split(",")
				var permissionKeys = _.keyBy(permissions,'ps_id')
				return cb(null,_.values(getPermissionsResult(permissionKeys,permissionIds)))
			});
		})
	})
}